import {
    getInsuranceRecharge,
    getIongInsuranceRechargeDetail
} from '../../api/insurance'
import {
    wxfileTobase64
} from '../../../utils/util.js'
import {
    getPayRechargeRecord,
    getAccountExpireNotify,
    getInsuranceProgramme,
    recharge
} from '../../../api/app'
import {
    dateFormat,
    toast
} from '../../../utils/util.js'
import user from '../../../utils/user'
import {
    getcompanyseatinfoapi,
    addrechargerecordapi
} from '../../api/seat'
let base64 = ''
Page({
    /**
     * 页面的初始数据
     */
    data: {
        avatar: user.avatarUrl,
        companyname: user.companyName,
        btntext: '上传汇款凭证',
        preview: '',
        showtips: false,
        contents: '',
        xwnum: 0,
        productflag: false,
        wxpayflag: false,
        gdgpayflag: true,
        tcprice: 0,
        tcpriceno: 0,
        lsprice: 0,
        ishdstatus: false,
        totalprice: 0,
        usedseat: 0,
        hasseat: 0,
        accountExpireTime: '',
        OtherBuySeatCnt: 0,
        flag: 0,
        bankName: user.bankName,
        bankNo: user.bankNo,
        openBank: user.openBank,
        bankLogo: user.bankLogo,
        receiptId: user.receiptId,
        mchid: user.mchid,
        qyWxQrcode: user.qyWxQrcode,
        channelName: user.channelName
    },
    async onLoad() {
        await user.waitLogin()
    },
    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        wx.loadFontFace({
            family: 'myfontfamily',
            // 将ttf格式的字体包上传到线上服务器，
            source: '../../../assets/D-DIN.ttf',
            success(res) {
                console.log(res.status, 'achsjhjachsjhjachsjhjachsjhj')
            },
            fail(res) {
                console.log(res.status)
            },
            complete(res) {
                console.log(res.status)
            }
        }),
        user.waitLogin().then(() => {
            this.setData({
                companyname: user.companyName,
                avatar: user.avatarUrl,
                bankName: user.bankName,
                bankNo: user.bankNo,
                openBank: user.openBank,
                bankLogo: user.bankLogo,
                receiptId: user.receiptId,
                mchid: user.mchid,
                qyWxQrcode: user.qyWxQrcode,
                contents: '银行卡号：' + user.bankNo + '，开户名称：' + user.openBank,
                channelName: user.channelName
            })
        })
        this.getcompanyseatinfo()
        this.getPrice()
    },

    getPrice() {
        Promise.all([getInsuranceProgramme({
            dictType: 'pay_account_plan',
        }), getInsuranceProgramme({
            dictType: 'pay_account_plan_unActivity',
        })]).then(resList => {
            const price1 = resList[0][0]
            const price2 = resList[1][0]
            this.setData({
                tcprice: price1?.dictValue * 1,
                tcpriceno: price2?.dictValue * 1,
                ishdstatus: price2?.status === '0' ? true : false,
                lsprice: (price2?.dictValue - price1?.dictValue) * 1
            })
            console.log(price1, price2, 'fsiugusu89gi')
        })
    },

    async getcompanyseatinfo() {
        let res = await getcompanyseatinfoapi()
        console.log(res, 'fuiyehg')
        let flag = 0
        if (res.seatList.length === 0) {
            flag = 0
        }
        if (res.seatList.length === 1) {
            flag = 1
        }
        if (res.seatList.length > 1) {
            flag = 2
        }
        this.setData({
            hasseat: res.hasSeat,
            usedseat: res.useSeat,
            accountExpireTime: res.accountExpireTime,
            OtherBuySeatCnt: res.OtherBuySeatCnt,
            flag: flag
        })
    },
    showtipfn() {
        this.setData({
            showtips: true
        })
    },
    selectwx() {
        this.setData({
            gdgpayflag: false,
            wxpayflag: true
        })
    },
    selectgdg() {
        this.setData({
            gdgpayflag: true,
            wxpayflag: false
        })
    },
    seleect() {
        this.setData({
            productflag: !this.data.productflag
        })
        if (this.data.productflag) {
            this.setData({
                totalprice: this.data.totalprice + this.data.tcprice
            })
        } else {
            this.setData({
                totalprice: this.data.totalprice - this.data.tcprice
            })
        }
    },
    closetip() {
        this.setData({
            showtips: false
        })
    },
    onClick() {
        this.setData({
            btntext: '提交'
        })
        this.selectComponent('#bottomFrame').showFrame()
    },
    // 点击取消之后
    onCancel(e) {
        console.log(e)
        // 恢复选中的数据
        this.setData({
            btntext: '上传汇款凭证'
        })
    },
    onUnload() {
        console.log('卸载啦')
        base64 = ''
    },
    // 点击确定之后
    onConfirm() {
        wx.showToast({
            icon: 'none',
            title: '点击了确定',
        })
    },
    async uploadc() {
        const result = await getAccountExpireNotify()
        let now = new Date().getTime()
        let overdate = new Date(result.accountExpireTime).getTime()
        if (now > overdate && !this.data.productflag) {
            wx.showToast({
                icon: 'none',
                title: '您的产品已经到期，续费后即可继续使用并购买席位。',
            })
            return
        }
        // if (this.data.btntext === '上传汇款凭证') {
        if (this.data.xwnum == 0 && !this.data.productflag) {
            wx.showToast({
                icon: 'none',
                title: '请选择要购买的产品',
            })
            return
        }
        // this.upload()
        // this.onClick()
        // } else {
        // if (base64 === '') {
        //     wx.showToast({
        //         icon: 'none',
        //         title: '请上传付款凭证',
        //     })
        //     return
        // }
        // let res = await addrechargerecordapi({
        //     payMoney: this.data.totalprice,
        //     rechargeAmount: 12,
        //     voucherUrl: base64,
        //     receiptId: this.data.receiptId,
        //     buySeatCount: this.data.xwnum,
        //     salesScenario: this.data.productflag && this.data.xwnum === 0 ? 1 : !this.data.productflag && this.data.xwnum !== 0 ? 2 : 3,
        //     payMode: this.data.wxpayflag ? 2 : 1,
        //     remark: this.data.productflag && this.data.xwnum === 0 ? '发薪专户续费 + 另购席位0个' : !this.data.productflag && this.data.xwnum !== 0 ? '另购席位' + this.data.xwnum + '个' : '发薪专户续费 + ' + '另购席位' + this.data.xwnum + '个'
        // })
        // if (res) {
        //     wx.reLaunch({
        //         url: '/packageInsurance/pages/bullet-admin-pay-success/bullet-admin-pay-success',
        //     })
        // }
        let res = await recharge({
            useWay: 'AccountRecharge',
            description: '发薪续费',
            mchid: '1673440814',
            amount: {
                total: this.data.totalprice
            },
            payer: {
                openid: user.openid,
            },
            attach: this.data.productflag && this.data.xwnum === 0 ? '{month: 12,paySeat: 0,salesScenario: 1}' : !this.data.productflag && this.data.xwnum !== 0 ? '{month: 12,paySeat: ' + this.data.xwnum + ',salesScenario: 2}' : '{month: 12,paySeat:  ' + this.data.xwnum + ',salesScenario: 3}'
        })
        console.log(res, '充值返回')
        res.package = res.packageValue
        wx.requestPayment(res).then(() => {
            wx.navigateTo({
                url: '/pages/success/success?title=充值成功&content=您可以稍后查看您的账户余额&opinion=0&back=2'
            })
        }, err => {
            console.log(err)
        })
        // }
    },
    upload() {
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            success: (res) => {
                wxfileTobase64(res.tempFilePaths[0]).then(base => {
                    base64 = base
                    console.log(base64, 'shufhuyi')
                    this.setData({
                        preview: res.tempFilePaths[0]
                    })
                })
            }
        })
    },
    preview() {
        wx.previewImage({
            urls: [this.data.preview],
        })
    },
    todetail() {
        wx.navigateTo({
            url: '/packageInsurance/pages/bullet-admin-detail/bullet-admin-detail',
        })
    },
    torechargehistory() {
        wx.navigateTo({
            url: '/packageInsurance/pages/bullet-recharge-history/bullet-recharge-history',
        })
    },
    // 长按保存功能--授权部分
    saveImage() {
        let curl = ''
        if (user.channelName === '苏州蓝豚') {
            curl = 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager517affd6-4bb8-40db-95ac-dc2afd61aa04.jpg'
        }
        if (user.channelName === '重庆蓝豚') {
            curl = 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager2003dab5-3c05-4bfd-85e9-0a37998edc6d.png'
        }
        let _this = this
        wx.showActionSheet({
            itemList: ['保存到相册'],
            success() {
                let url = curl
                wx.getSetting({
                    success: (res) => {
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            wx.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success: () => {
                                    // 同意授权
                                    _this.saveImgInner(url)
                                },
                                fail: (res) => {
                                    console.log(res)
                                    wx.showModal({
                                        title: '保存失败',
                                        content: '请开启访问手机相册权限',
                                        success() {
                                            wx.openSetting()
                                        }
                                    })
                                }
                            })
                        } else {
                            // 已经授权了
                            _this.saveImgInner(url)
                        }
                    },
                    fail: (res) => {
                        console.log(res)
                    }
                })
            },
            fail(res) {
                console.log(res.errMsg)
            }
        })
    },
    // 长按保存功能--保存部分
    saveImgInner(url) {
        wx.getImageInfo({
            src: url,
            success: (res) => {
                let path = res.path
                wx.saveImageToPhotosAlbum({
                    filePath: path,
                    success: (res) => {
                        console.log(res)
                        wx.showToast({
                            title: '已保存到相册',
                        })
                    },
                    fail: (res) => {
                        console.log(res)
                    }
                })
            },
            fail: (res) => {
                console.log(res)
            }
        })
    },
    copyText(e) {
        console.log(e)
        wx.setClipboardData({
            data: e.currentTarget.dataset.text,
            success: function () {
                wx.getClipboardData({
                    success: function () {
                        wx.showToast({
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    },
    handleInput(e) {
        let value = this.validateNumber(e.detail.value)
        if (value * 1 < 0) {
            return
        }
        let val = value + ''
        let arr = val.split('')
        if (arr.length === 2 && arr[0] === '0') {
            value = arr[1] * 1
        }
        this.setData({
            xwnum: value,
            totalprice: value * 300
        })
    },
    validateNumber(val) {
        if (!val) return 0
        // val = val.replace(/\s*/g, '')
        return val.replace(/\s*/g, '').replace(/\D/g, '')
    },
    add() {
        let num = this.data.xwnum * 1 + 1
        this.setData({
            xwnum: num,
            totalprice: this.data.totalprice + 300
        })
    },
    unadd() {
        let num = this.data.xwnum * 1 - 1
        if (num < 0) {
            return
        }
        this.setData({
            xwnum: num,
            totalprice: this.data.totalprice - 300
        })
    }
})